const { login } = require('../controller/user')
const { SuccessModel, ErrorModel } = require('../model/resModel')

//获取cookie的过期时间
const getCookieExpires = () => {
    const d = new Date()
    d.setTime(d.getTime() + (24 * 60 * 60 * 1000))
    console.log('d.toGMTString() is',d.toGMTString())
    return d.toGMTString()

}



const handleUserRouter = (req, res) => {
    const method = req.method
    const url = req.url
    const path = url.split('?')[0]
    // console.log(req.body)
    //登录
    if (method === "GET" && path === "/api/user/login") {
        // const { username, password } = req.body
        // console.log(req.query)
        const { username, password } = req.query
        const result = login(username, password)
        return result.then(data => {
            if (data.username) {
                // console.log('data.realname is',data.realname)
                // console.log('data.username is',username)
                //设置cookie
                res.setHeader('Set-Cookie', `username=${data.realname}; path=/; httpOnly; expires=${getCookieExpires()}`)

                return new SuccessModel("登录成功")
            }
            return new ErrorModel("登录失败")
        })

    }
<<<<<<< HEAD


    //登录验证的测试
    if (method === 'GET' && path === '/api/user/login-test') {
        // console.log(req.headers.cookie.split('=')[1])
        if (req.headers.cookie) {
            return Promise.resolve(new SuccessModel({
                realname: req.headers.cookie.split('=')[1]
            }
            ))
        }

        return Promise.resolve(new ErrorModel('登录失败'))
    }




=======
>>>>>>> a923843304d18e996b46c69f246fcc4a66824b12
}

module.exports = handleUserRouter






